<?php


function get_now_url(){
	
	return 'http://'.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]; 
}

function get_username($uid){
	return	D("Users")->where(array("id"=>$uid))->getField('nickname');
	
}
function get_companyname($uid){

	return	D("Company")->where(array("id"=>$uid))->getField('companyname');
		
}

function lap_ajax_return($data,$info,$status){
	$info = array();
	$info['data'] = $data;
	$info['info'] = $info;
	$info['status'] = $status;
	$data = $info;

	return $data;
}


/**
 * 返回带协议的域名
 */
function lap_get_host(){
	$host=$_SERVER["HTTP_HOST"];
	$protocol=is_ssl()?"https://":"http://";
	return $protocol.$host;
}


//调用TagLib类
function TagLib($name, $params = array()) {
	$class = $name . 'TagLib';
	import("TagLib.{$class}"," /Home/Taglib");
	return instance($class, '', $params);
}


/**
 * 获取前台模板根目录
 */
function lap_get_theme_path(){
	// 获取当前主题名称
	$tmpl_path=C("LAP_TMPL_PATH");
	$theme      =    C('LAP_DEFAULT_THEME');
	if(C('TMPL_DETECT_THEME')) {// 自动侦测模板主题
		$t = C('VAR_TEMPLATE');
		if (isset($_GET[$t])){
			$theme = $_GET[$t];
		}elseif(cookie('think_template')){
			$theme = cookie('think_template');
		}
		if(!file_exists($tmpl_path."/".$theme)){
			$theme  =   C('LAP_DEFAULT_THEME');
		}
		cookie('think_template',$theme,864000);
	}

	return __ROOT__.'/'.$tmpl_path.$theme."/";
}


/**
 * 获取用户头像相对网站根目录的地址
 */
function lap_get_user_avatar_url($avatar){
	
	if($avatar){
		if(strpos($avatar, "http")===0){
			return $avatar;
		}else {
			return __ROOT__."/".C("UPLOADPATH")."avatar/".$avatar;
		}
		
	}else{
		return $avatar;
	}
	
}
function lap_password($pw,$key){
	

	
	return $key?md5(md5($pw).$key.C('DATA_AUTH_KEY')):md5($pw.C('DATA_AUTH_KEY'));
	
}

function lap_log($content,$file="log.txt"){
	file_put_contents($file, $content,FILE_APPEND);
}

function lap_random_string($len = 6) {
	$chars = array(
			"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
			"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
			"w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
			"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
			"S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
			"3", "4", "5", "6", "7", "8", "9"
	);
	$charsLen = count($chars) - 1;
	shuffle($chars);    // 将数组打乱
	$output = "";
	for ($i = 0; $i < $len; $i++) {
		$output .= $chars[mt_rand(0, $charsLen)];
	}
	return $output;
}





/**
 * 保存变量
 */
function lap_save_var($path,$value){
	$ret = file_put_contents($path, "<?php\treturn " . var_export($value, true) . ";?>");
	return $ret;
}

function lap_set_dynamic_config($data){
	if(defined('IS_SAE') && IS_SAE){
		$kv = new SaeKV();
		$ret = $kv->init();
		$configs=$kv->get("THINKCMF_DYNAMIC_CONFIG");
		$configs=empty($configs)?array():unserialize($configs);
		$configs=array_merge($configs,$data);
		$result = $kv->set('THINKCMF_DYNAMIC_CONFIG', serialize($configs));
	}elseif(defined('IS_BAE') && IS_BAE){
		$bae_mc=new BaeMemcache();
		$configs=$bae_mc->get("THINKCMF_DYNAMIC_CONFIG");
		$configs=empty($configs)?array():unserialize($configs);
		$configs=array_merge($configs,$data);
		$result = $bae_mc->set("THINKCMF_DYNAMIC_CONFIG",serialize($configs),MEMCACHE_COMPRESSED,0);
	}else{
		$config_file="./data/conf/config.php";
		if(file_exists($config_file)){
			$configs=include $config_file;
		}else {
			$configs=array();
		}
		$configs=array_merge($configs,$data);
		$result = file_put_contents($config_file, "<?php\treturn " . var_export($configs, true) . ";?>");
	}
	lap_clear_cache();
	return $result;
}


/**
 * 生成参数列表,以数组形式返回
 */
function lap_param_lable($tag = ''){
	$param = array();
	$array = explode(';',$tag);
	foreach ($array as $v){
		$v=trim($v);
		if(!empty($v)){
			list($key,$val) = explode(':',$v);
			$param[trim($key)] = trim($val);
		}
	}
	return $param;
}


/**
 * 
 */




function lap_get_cmf_settings($key=""){
	$cmf_settings = F("cmf_settings");
	if(empty($cmf_settings)){
		$options_obj = M("Options");
		$option = $options_obj->where("option_name='cmf_settings'")->find();
		if($option){
			$cmf_settings = json_decode($option['option_value'],true);
		}else{
			$cmf_settings = array();
		}
		F("cmf_settings", $cmf_settings);
	}
	if(!empty($key)){
		return $cmf_settings[$key];
	}
	return $cmf_settings;
}












/**
 * 11
 * @param string $content
 * @return array
 */
function lap_getcontent_imgs($content){
	import("phpQuery");
	phpQuery::newDocumentHTML($content);
	$pq=pq();
	$imgs=$pq->find("img");
	$imgs_data=array();
	if($imgs->length()){
		foreach ($imgs as $img){
			$img=pq($img);
			$im['src']=$img->attr("src");
			$im['title']=$img->attr("title");
			$im['alt']=$img->attr("alt");
			$imgs_data[]=$im;
		}
	}
	phpQuery::$documents=null;
	return $imgs_data;
}

/*
 * 作用：写入新消息
 * 参数：$from	发送者id
 * 		$to		消息接受者id
 * 		$content  消息内容
 * 		$targetid 相应数据表中的id的值
 * 		$mestype可选值：topic_comment(话题评论)、topic_answer(话题回复)、topic_collect(话题收藏)、topic_love(喜欢)
 */
function insertMes($from, $to, $content, $targetid, $mestype){
	$data = array(
			'mes_from'	=> $from,
			'mes_to'	=> $to,
			'mes_content' => $content,
			'post_time'	=> time(),
			'target_id'	=> $targetid,
			'mes_type'	=> $mestype,
			'mes_status'=> '2', //未读
	);
	return M('Message')->add($data);
}


/**
 * 
 * @param unknown_type $navcatname
 * @param unknown_type $datas
 * @param unknown_type $navrule
 * @return string
 */
function lap_get_nav4admin($navcatname,$datas,$navrule){
	$nav['name']=$navcatname;
	$nav['urlrule']=$navrule;
	foreach($datas as $t){
		$urlrule=array();
		$group=strtolower(MODULE_NAME)==strtolower(C("DEFAULT_MODULE"))?"":MODULE_NAME."/";
		$action=$group.$navrule['action'];
		$urlrule['action']=MODULE_NAME."/".$navrule['action'];
		$urlrule['param']=array();
		if(isset($navrule['param'])){
			foreach ($navrule['param'] as $key=>$val){
				$urlrule['param'][$key]=$t[$val];
			}
		}
		
		$nav['items'][]=array(
				"label"=>$t[$navrule['label']],
				"url"=>U($action,$urlrule['param']),
				"rule"=>serialize($urlrule)
		);
	}
	return json_encode($nav);
}

function lap_get_apphome_tpl($tplname,$default_tplname,$default_theme=""){
	$theme      =    C('LAP_DEFAULT_THEME');
	if(C('TMPL_DETECT_THEME')){// 自动侦测模板主题
		$t = C('VAR_TEMPLATE');
		if (isset($_GET[$t])){
			$theme = $_GET[$t];
		}elseif(cookie('think_template')){
			$theme = cookie('think_template');
		}
	}
	$theme=empty($default_theme)?$theme:$default_theme;
	$themepath=C("LAP_TMPL_PATH").$theme."/".MODULE_NAME."/";
	$tplpath=$themepath.$tplname.C("TMPL_TEMPLATE_SUFFIX");
	$defaultpl=$themepath.$default_tplname.C("TMPL_TEMPLATE_SUFFIX");
	if(file_exists($tplpath)){
	}else if(file_exists($defaultpl)){
		$tplname=$default_tplname;
	}else{
		$tplname="404";
	}
	return $tplname;
}

//面包屑导航
function lap_bread_nav($nav_id){
	$navTable = M('Nav');
	$path = $navTable->where("id=$nav_id")->getField('path');
	if(!$path) return array();
	$path = str_replace('-',',',$path);
	$bread_path = $navTable->where("id in ($path)")->order('id')->select();
	return $bread_path;
}

/*
 * 作用：去除字符串中的指定字符
 * 参数: $str, string, 待处理字符串
 *       $chars, string, 需去掉的特殊字符
 */
function lap_strip_chars($str, $chars='?<*.>\'\"'){
	return preg_replace('/['.$chars.']/is', '', $str);
}






function lap_get_asset_upload_path($file,$withhost=false){
	if(strpos($file,"http")===0){
		return $file;
	}else if(strpos($file,"/")===0){
		return $file;
	}else{
		$filepath=C("TMPL_PARSE_STRING.__UPLOAD__").$file;
		if($withhost){
			if(strpos($filepath,"http")!==0){
				$http = 'http://';
				$http =is_ssl()?'https://':$http;
				$filepath = $http.$_SERVER['HTTP_HOST'].$filepath;
			}
		}
		return $filepath;
		
	}                    			
                        		
}


function lap_authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
	$ckey_length = 4;

	$key = md5($key ? $key : C("AUTHCODE"));
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}

}

function lap_authencode($string){
	return lap_authcode($string,"ENCODE");
}

function Comments($table,$post_id,$params=array()){
	return  R("Comment/Widget/index",array($table,$post_id,$params));
}
/**
 * 获取评论
 * @param string $tag
 * @param array $where //按照thinkphp where array格式
 */
function lap_get_comments($tag="field:*;limit:0,5;order:createtime desc;",$where=array()){
	$where=array();
	$tag=lap_param_lable($tag);
	$field = !empty($tag['field']) ? $tag['field'] : '*';
	$limit = !empty($tag['limit']) ? $tag['limit'] : '5';
	$order = !empty($tag['order']) ? $tag['order'] : 'createtime desc';
	
	//根据参数生成查询条件
	$mwhere['status'] = array('eq',1);
	
	if(is_array($where)){
		$where=array_merge($mwhere,$where);
	}else{
		$where=$mwhere;
	}
	
	$comments_model=M("Comments");
	
	$comments=$comments_model->field($field)->where($where)->order($order)->limit($limit)->select();
	return $comments;
}

function lap_file_write($file,$content){
	
	if(defined('IS_SAE') && IS_SAE){
		$s=new SaeStorage();
		$arr=explode('/',ltrim($file,'./'));
		$domain=array_shift($arr);
		$save_path=implode('/',$arr);
		return $s->write($domain,$save_path,$content);
	}else{
		try {
			$fp2 = @fopen( $file , "w" );
			fwrite( $fp2 , $content );
			fclose( $fp2 );
			return true;
		} catch ( Exception $e ) {
			return false;
		}
	}
}

function lap_asset_relative_url($asset_url){
	return str_replace(C("TMPL_PARSE_STRING.__UPLOAD__"), "", $asset_url);
}

function lap_content_page($content,$pagetpl='{first}{prev}&nbsp;{liststart}{list}{listend}&nbsp;{next}{last}'){
	$contents=explode('_ueditor_page_break_tag_',$content);
	$totalsize=count($contents);
	import('Page');
	$pagesize=1;
	$PageParam = C("VAR_PAGE");
	$page = new \Page($totalsize,$pagesize);
	$page->setLinkWraper("li");
	$page->SetPager('default', $pagetpl, array("listlong" => "6", "first" => "首页", "last" => "尾页", "prev" => "上一页", "next" => "下一页", "list" => "*", "disabledclass" => ""));
	$content=$contents[$page->firstRow];
	$data['content']=$content;
	$data['page']=$page->show('default');

	return $data;
}








/**
 * 检查用户对某个url,内容的可访问性，用于记录如是否赞过，是否访问过等等;开发者可以自由控制，对于没有必要做的检查可以不做，以减少服务器压力
 * @param number $object 访问对象的id,格式：不带前缀的表名+id;如posts1表示xx_posts表里id为1的记录;如果object为空，表示只检查对某个url访问的合法性
 * @param number $count_limit 访问次数限制,如1，表示只能访问一次
 * @param boolean $ip_limit ip限制,false为不限制，true为限制
 * @param number $expire 距离上次访问的最小时间单位s，0表示不限制，大于0表示最后访问$expire秒后才可以访问
 * @return true 可访问，false不可访问
 */
function lap_check_user_action($object="",$count_limit=1,$ip_limit=false,$expire=0){
	$common_action_log_model=M("CommonActionLog");
	$action=MODULE_NAME."-".CONTROLLER_NAME."-".ACTION_NAME;
	$userid=get_current_userid();
	
	$ip=get_client_ip();
	
	$where=array("user"=>$userid,"action"=>$action,"object"=>$object);
	if($ip_limit){
		$where['ip']=$ip;
	}
	
	$find_log=$common_action_log_model->where($where)->find();
	
	$time=time();
	if($find_log){
		$common_action_log_model->where($where)->save(array("count"=>array("exp","count+1"),"last_time"=>$time,"ip"=>$ip));
		if($find_log['count']>=$count_limit){
			return false;
		}
		
		if($expire>0 && ($time-$find_log['last_time'])<$expire){
			return false;
		}
	}else{
		$common_action_log_model->add(array("user"=>$userid,"action"=>$action,"object"=>$object,"count"=>array("exp","count+1"),"last_time"=>$time,"ip"=>$ip));
	}
	
	return true;
}
/**
 * 用于生成收藏内容用的key
 * @param string $table 收藏内容所在表
 * @param int $object_id 收藏内容的id
 */
function lap_get_favorite_key($table,$object_id){
	$auth_code=C("AUTHCODE");
	$string="$auth_code $table $object_id";
	
	return lap_authencode($string);
}


function lap_get_relative_url($url){
	if(strpos($url,"http")===0){
		$url=str_replace(array("https://","http://"), "", $url);
		
		$pos=strpos($url, "/");
		if($pos===false){
			return "";
		}else{
			$url=substr($url, $pos+1);
			$root=preg_replace("/^\//", "", __ROOT__);
			$root=str_replace("/", "\/", $root);
			$url=preg_replace("/^".$root."\//", "", $url);
			return $url;
		}
	}
	return $url;
}

/**
 * 
 * @param string $tag
 * @param array $where
 * @return array
 */

function lap_get_users($tag="field:*;limit:0,8;order:create_time desc;",$where=array()){
	$where=array();
	$tag=lap_param_lable($tag);
	$field = !empty($tag['field']) ? $tag['field'] : '*';
	$limit = !empty($tag['limit']) ? $tag['limit'] : '8';
	$order = !empty($tag['order']) ? $tag['order'] : 'create_time desc';
	
	//根据参数生成查询条件
	$mwhere['user_status'] = array('eq',1);
	$mwhere['user_type'] = array('eq',2);//default user
	
	if(is_array($where)){
		$where=array_merge($mwhere,$where);
	}else{
		$where=$mwhere;
	}
	
	$comments_model=M("Users");
	
	$comments=$comments_model->field($field)->where($where)->order($order)->limit($limit)->select();
	return $comments;
}



/**
 * 检测验证码
 * @param  integer $id 验证码ID
 * @return boolean     检测结果
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function check_verify($code, $id = 1){
	$verify = new \Think\Verify();
	return $verify->check($code, $id);
}



/**
 * 系统加密方法
 * @param string $data 要加密的字符串
 * @param string $key  加密密钥
 * @param int $expire  过期时间 单位 秒
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function think_encrypt($data, $key = '', $expire = 0) {
	$key  = md5(empty($key) ? C('DATA_AUTH_KEY') : $key);
	$data = base64_encode($data);
	$x    = 0;
	$len  = strlen($data);
	$l    = strlen($key);
	$char = '';

	for ($i = 0; $i < $len; $i++) {
		if ($x == $l) $x = 0;
		$char .= substr($key, $x, 1);
		$x++;
	}

	$str = sprintf('%010d', $expire ? $expire + time():0);

	for ($i = 0; $i < $len; $i++) {
		$str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1)))%256);
	}
	return str_replace(array('+','/','='),array('-','_',''),base64_encode($str));
}

/**
 * 系统解密方法
 * @param  string $data 要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @param  string $key  加密密钥
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function think_decrypt($data, $key = ''){
	$key    = md5(empty($key) ? C('DATA_AUTH_KEY') : $key);
	$data   = str_replace(array('-','_'),array('+','/'),$data);
	$mod4   = strlen($data) % 4;
	if ($mod4) {
		$data .= substr('====', $mod4);
	}
	$data   = base64_decode($data);
	$expire = substr($data,0,10);
	$data   = substr($data,10);

	if($expire > 0 && $expire < time()) {
		return '';
	}
	$x      = 0;
	$len    = strlen($data);
	$l      = strlen($key);
	$char   = $str = '';

	for ($i = 0; $i < $len; $i++) {
		if ($x == $l) $x = 0;
		$char .= substr($key, $x, 1);
		$x++;
	}

	for ($i = 0; $i < $len; $i++) {
		if (ord(substr($data, $i, 1))<ord(substr($char, $i, 1))) {
			$str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
		}else{
			$str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
		}
	}
	return base64_decode($str);
}

/**
 * 数据签名认证
 * @param  array  $data 被认证的数据
 * @return string       签名
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function data_auth_sign($data) {
	//数据类型检测
	if(!is_array($data)){
		$data = (array)$data;
	}
	ksort($data); //排序
	$code = http_build_query($data); //url编码并生成query字符串
	$sign = sha1($code); //生成签名
	return $sign;
}

/**
 * 获取模版文件 格式 主题://模块/控制器/方法
 * @param type $templateFile
 * @return boolean|string
 */
function parseTemplateFile($templateFile = '') {
	static $TemplateFileCache = array();
	//模板路径
	$TemplatePath = TEMPLATE_PATH;
	//模板主题
	$Theme = C('DEFAULT_THEME')? C('DEFAULT_THEME'):'Default';
	//如果有指定 GROUP_MODULE 则模块名直接是GROUP_MODULE，否则使用 MODULE_NAME，这样做的目的是防止其他模块需要生成
	$group = defined('GROUP_MODULE') ? GROUP_MODULE : MODULE_NAME;
	//兼容 Add:ss 这种写法
	if (!empty($templateFile) && strpos($templateFile, ':') && false === strpos($templateFile, C('TMPL_TEMPLATE_SUFFIX'))) {
		if (strpos($templateFile, '://')) {
			$temp = explode('://', $templateFile);
			$fxg = str_replace(':', '/', $temp[1]);
			$templateFile = $temp[0] . $fxg;
		} else {
			$templateFile = str_replace(':', '/', $templateFile);
		}
	}
	if ($templateFile != '' && strpos($templateFile, '://')) {
		$exp = explode('://', $templateFile);
		$Theme = $exp[0];
		$templateFile = $exp[1];
	}
	// 分析模板文件规则
	$depr = C('TMPL_FILE_DEPR');
	//模板标识
	if ('' == $templateFile) {
		$templateFile = $TemplatePath . $Theme . '/' . $group . '/' . CONTROLLER_NAME . '/' . ACTION_NAME . C('TMPL_TEMPLATE_SUFFIX');
	}
	$key = md5($templateFile);
	if (isset($TemplateFileCache[$key])) {
		return $TemplateFileCache[$key];
	}
	if (false === strpos($templateFile, '/') && false === strpos($templateFile, C('TMPL_TEMPLATE_SUFFIX'))) {
		$templateFile = $TemplatePath . $Theme . '/' . $group . '/' . CONTROLLER_NAME . '/' . $templateFile . C('TMPL_TEMPLATE_SUFFIX');
	} else if (false === strpos($templateFile, C('TMPL_TEMPLATE_SUFFIX'))) {
		$path = explode('/', $templateFile);
		$action = array_pop($path);
		$controller = !empty($path) ? array_pop($path) : CONTROLLER_NAME;
		if (!empty($path)) {
			$group = array_pop($path)? : $group;
		}
		$depr = defined('MODULE_NAME') ? C('TMPL_FILE_DEPR') : '/';
		$templateFile = $TemplatePath . $Theme . '/' . $group . '/' . $controller . $depr . $action . C('TMPL_TEMPLATE_SUFFIX');
	}
	//区分大小写的文件判断，如果不存在，尝试一次使用默认主题
	if (!file_exists_case($templateFile)) {
		$log = '模板:[' . $templateFile . '] 不存在！';
		\Think\Log::record($log);
		//启用默认主题模板
		$templateFile = str_replace($TemplatePath . $Theme, $TemplatePath . 'Default', $templateFile);
		//判断默认主题是否存在，不存在直接报错提示
		if (!file_exists_case($templateFile)) {
			if (defined('APP_DEBUG') && APP_DEBUG) {
				E($log);
			}
			$TemplateFileCache[$key] = false;
			return false;
		}
	}
	$TemplateFileCache[$key] = $templateFile;
	return $TemplateFileCache[$key];
}
/**
 * 截取字符串中两个特殊字符之间的内容
 * @param type $templateFile
 * @return boolean|string
 */
function substr_between($string, $start, $end=null) {
	if(($start_pos = strpos($string, $start)) !== false) {
		if($end) {
			if(($end_pos = strpos($string, $end, $start_pos + strlen($start))) !== false) {
				return substr($string, $start_pos + strlen($start), $end_pos - ($start_pos + strlen($start)));
			}
		} else {
			return substr($string, $start_pos);
		}
	}
	return false;
}


function in_array_string($data,$array,$dot=","){
	$s=explode($dot,$array);
	
	if(in_array($data, $s)){
		
		return true;
	}else{
		return false;
	}
	
	
	
	
	
}

 function return_url($value){
	$arr=explode(".", $_SERVER['REQUEST_URI']);
	$array=explode("/", $arr[0]);
	$len=strlen(__ROOT__."/$value/");
	if(in_array("p", $array)){
		$p_index=stripos($arr[0], 'p');
		$url_can=substr($arr[0], 0,$p_index-1);
		$url=substr($url_can, $len);
	}else{
		$url=substr($arr[0],$len);
	}

	if(!empty($url)){
		$url="/".$url."/";
	}else{
		$url="/";
	}
	return $url;
}

/**
 * 分页处理
 * @param type $total 信息总数
 * @param type $size 每页数量
 * @param type $number 当前分页号（页码）
 * @param type $config 配置，会覆盖默认设置
 * @return \Page|array
 */
function page($total, $size = 0, $number = 0, $config = array()) {
    //配置
    $defaultConfig = array(
        //当前分页号
        'number' => $number,
        //接收分页号参数的标识符
        'param' => C("VAR_PAGE"),
        //分页规则
        'rule' => '',
        //是否启用自定义规则
        'isrule' => false,
        //分页模板
        'tpl' => '',
        //分页具体可控制配置参数默认配置
        'tplconfig' => array('listlong' => 6, 'listsidelong' => 2, "first" => "首页", "last" => "尾页", "prev" => "上一页", "next" => "下一页", "list" => "*", "disabledclass" => ""),
    );
    //分页具体可控制配置参数
    $cfg = array(
        //每次显示几个分页导航链接
        'listlong' => 6,
        //分页链接列表首尾导航页码数量，默认为2，html 参数中有”{liststart}”或”{listend}”时才有效
        'listsidelong' => 2,
        //分页链接列表
        'list' => '*',
        //当前页码的CSS样式名称，默认为”current”
        'currentclass' => 'current',
        //第一页链接的HTML代码，默认为 ”«”，即显示为 «
        'first' => '&laquo;',
        //上一页链接的HTML代码，默认为”‹”,即显示为 ‹
        'prev' => '&#8249;',
        //下一页链接的HTML代码，默认为”›”,即显示为 ›
        'next' => '&#8250;',
        //最后一页链接的HTML代码，默认为”»”,即显示为 »
        'last' => '&raquo;',
        //被省略的页码链接显示为，默认为”…”
        'more' => '...',
        //当处于首尾页时不可用链接的CSS样式名称，默认为”disabled”
        'disabledclass' => 'disabled',
        //页面跳转方式，默认为”input”文本框，可设置为”select”下拉菜单
        'jump' => '',
        //页面跳转文本框或下拉菜单的附加内部代码
        'jumpplus' => '',
        //跳转时要执行的javascript代码，用*代表页码，可用于Ajax分页
        'jumpaction' => '',
        //当跳转方式为下拉菜单时最多同时显示的页码数量，0为全部显示，默认为50
        'jumplong' => 50,
    );
    //覆盖配置
    if (!empty($config) && is_array($config)) {
        $defaultConfig = array_merge($defaultConfig, $config);
    }
    //每页显示信息数量
    $defaultConfig['size'] = $size ? $size : C("PAGE_LISTROWS");
    //把默认配置选项设置到tplconfig
    foreach ($cfg as $key => $value) {
        if (isset($defaultConfig[$key])) {
            $defaultConfig['tplconfig'][$key] = isset($defaultConfig[$key]) ? $defaultConfig[$key] : $value;
        }
    }
//     //是否启用自定义规则，规则是一个数组，index和list。不启用的情况下，直接以当前$_GET的参数组成地址
//     if ($defaultConfig['isrule'] && empty($defaultConfig['rule'])) {
//         //通过全局参数获取分页规则
//         $URLRULE = isset($GLOBALS['URLRULE']) ? $GLOBALS['URLRULE'] : (defined('URLRULE') ? URLRULE : '');
//         $PageLink = array();
//         if (!is_array($URLRULE)) {
//             $URLRULE = explode('~', $URLRULE);
//         }
//         $PageLink['index'] = isset($URLRULE['index']) && $URLRULE['index'] ? $URLRULE['index'] : $URLRULE[0];
//         $PageLink['list'] = isset($URLRULE['list']) && $URLRULE['list'] ? $URLRULE['list'] : $URLRULE[1];
//         $defaultConfig['rule'] = $PageLink;
//     } else if ($defaultConfig['isrule'] && !is_array($defaultConfig['rule'])) {
//         $URLRULE = explode('|', $defaultConfig['rule']);
//         $PageLink = array();
//         $PageLink['index'] = $URLRULE[0];
//         $PageLink['list'] = $URLRULE[1];
//         $defaultConfig['rule'] = $PageLink;
//     }
    import("Page");
    $Page = new \Page($total, $defaultConfig['size'], $defaultConfig['number'], $defaultConfig['list'], $defaultConfig['param'], $defaultConfig['rule'], $defaultConfig['isrule']);
    $Page->SetPager('default', $defaultConfig['tpl'], $defaultConfig['tplconfig']);
    return $Page;
	}




function SendMail($address, $title, $message) {
    $config = F('Config_mail');
    import('PHPMailer');
    try {
        $mail = new \PHPMailer();
        $mail->IsSMTP();
        // 设置邮件的字符编码，若不指定，则为'UTF-8'
        $mail->CharSet = C("DEFAULT_CHARSET");
        $mail->IsHTML(true);
        // 添加收件人地址，可以多次使用来添加多个收件人
        if (is_array($address)) {
            foreach ($address as $k => $v) {
                if (is_array($v)) {
                    $mail->AddAddress($v[0], $v[1]);
                } else {
                    $mail->AddAddress($v);
                }
            }
        } else {
            $mail->AddAddress($address);
        }
        // 设置邮件正文
        $mail->Body = $message;
        // 设置邮件头的From字段。
        $mail->From = $config['MAIL_ADDRESS'];
        // 设置发件人名字
        $mail->FromName = $config['MAIL_NAME'];
        // 设置邮件标题
        $mail->Subject = $title;
        // 设置SMTP服务器。
        $mail->Host = $config['MAIL_SEVER'];
        // 设置为“需要验证”
        if ($config['MAIL_YANZHENG']) {
            $mail->SMTPAuth = true;
        } else {
            $mail->SMTPAuth = false;
        }
        // 设置用户名和密码。
        $mail->Username = $config['SITE_USER'];
        $mail->Password = $config['SITE_PASSWORD'];
        return $mail->Send();
    } catch (phpmailerException $e) {
        return $e->errorMessage();
    }
}


 function ToXml($data)
{
	if(!is_array($data)
		|| count($data) <= 0)
	{
		throw new WxPayException("数组数据异常！");
	}

	$xml = "<xml>";
	foreach ($data as $key=>$val)
	{
		if (is_numeric($val)){
			$xml.="<".$key.">".$val."</".$key.">";
		}else{
			$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
		}
	}
	$xml.="</xml>";
	return $xml;
}



/**
 * 发送短信通知
 * @param $number
 * @param $tpl
 * @param $data
 */
function send_message($number, $tpl, $data){

	Header("Content-Type:text/html;charset=utf-8");
	Vendor('taobao.TopSdk');

	$c = new \TopClient;
	$c->appkey = "24561614";
	$c->secretKey = "b22e53c0518cd1da84d2215b9edb3301";
	$req = new \AlibabaAliqinFcSmsNumSendRequest;
	$req ->setExtend( "" );
	$req ->setSmsType( "normal" );
	$req ->setSmsFreeSignName( "金货郎" );
	$req ->setSmsParam(json_encode($data));
	$req ->setRecNum( $number );
	$req ->setSmsTemplateCode( $tpl );
	$resp = $c ->execute( $req );

	return $resp;




}

